package prv.pursuivant.render.html;

import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Date;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import prv.pursuivant.core.AchievType;
import prv.pursuivant.core.AchievTypesTree;
import prv.pursuivant.render.Destination;
import prv.pursuivant.render.ModelRenderer;
import prv.pursuivant.render.OutputGenerator;
import prv.pursuivant.render.PageContentRenderer;
import prv.pursuivant.render.PageDecorationRenderer;

import com.google.inject.Inject;

public class HtmlModelRenderer implements ModelRenderer {

	private final Collection<String> activeAchievs;
	private final AchievTypesTree tree;
	private final Destination destination;
	private final PageDecorationRenderer pageDecorationRenderer;
	private final PageContentRenderer pageContentRenderer;

	@Inject
	public HtmlModelRenderer(Destination destination,
			PageDecorationRenderer pageDecorationRenderer,
			PageContentRenderer pageContentRenderer, AchievTypesTree tree,
			Collection<String> activeAchievs) {
		this.destination = destination;
		this.pageDecorationRenderer = pageDecorationRenderer;
		this.pageContentRenderer = pageContentRenderer;
		this.tree = tree;
		this.activeAchievs = activeAchievs;
	}

	@Override
	public void renderModel(Date when) throws IOException {
		destination.startModel("");
		for (String achievId : activeAchievs) {
			renderPage(tree.findAchievTypeById(achievId), when);
		}
		destination.stopModel();
	}

	@Override
	public void renderPage(AchievType achiev, Date when) throws IOException {
		Writer writer = destination.startPage(achiev.getId());

		final XMLOutputFactory factory = XMLOutputFactory.newInstance();
		XMLStreamWriter createXMLStreamWriter;
		try {
			createXMLStreamWriter = factory.createXMLStreamWriter(writer);
		} catch (XMLStreamException e) {
			throw new UnsupportedOperationException(e);
		}
		OutputGenerator generator = new XHtmlGenerator(createXMLStreamWriter);
		generator.startDocument();

		pageDecorationRenderer.renderPageHeader(generator, achiev, when);
		pageContentRenderer.renderPageContent(generator, achiev, when);
		pageDecorationRenderer.renderPageFooter(generator, achiev, when);

		generator.endDocument();
		destination.stopPage();
	}

}
